<?php
/*
 * This file is part of the Administrator/xiaoweiyuanwuye.
 *
 * (c) Administrator <Administrator@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace app\admin\controller\dingtalk;

use app\common\controller\Backend;
use app\common\model\DingtalkUser;
use ChenDingtalk\DingtalkException;
use ChenDingtalk\DingtalkManager;

class User extends Backend
{
    /**
     * @var DingtalkManager
     */
    protected $dingtalk;

    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->dingtalk = new DingtalkManager(config('dingtalk'));
        $this->model = new DingtalkUser();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            try {
                $this->dingtalk->user()->create($params);
            } catch (DingtalkException $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        return $this->fetch('form');
    }

    public function edit($ids = NULL)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $params['id'] = $ids;
            try {
                $this->dingtalk->user()->update($params);
            } catch (DingtalkException $e) {
                $this->error($e->getMessage());
            }

            $this->success();
        }
        $row = (array)$this->dingtalk->user()->get($ids);
        $this->assign('row', $row);
        return $this->fetch('form');
    }

    public function detail()
    {

    }

    public function del($ids = "")
    {
        $ids = explode(',', $ids);
        try {
            foreach ($ids as $id) {
                $this->dingtalk->user()->delete($id);
            }
        } catch (DingtalkException $e) {
            $this->error($e->getMessage());
        }
        $this->success();
    }
}